package com.depth.viewer.manager
{
	import com.depth.viewer.events.AppEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.system.ApplicationDomain;
	
	import mx.core.FlexGlobals;
	import mx.events.StyleEvent;
	import mx.styles.IStyleManager2;
	
	public class ViewerStyleManager extends EventDispatcher implements IViewerStyleManager
	{
		
		private static var instance:IViewerStyleManager;
		
		private var _sourcesUrl:Array = [];
		public function ViewerStyleManager()
		{
			
		}
		private function loadNextCssStyle():void{
			if(_sourcesUrl.length > 0){
				var url:String = _sourcesUrl.shift();
				loadCssStyle(url);
			}
		}
		public function loadCssStyle(source:String):void{
			//_sourcesUrl.push(source);
			var styleLoader:IEventDispatcher = IStyleManager2(FlexGlobals.topLevelApplication.styleManager).loadStyleDeclarations(source,false,ApplicationDomain.currentDomain);//加载字体swf 
			
			styleLoader.addEventListener(StyleEvent.COMPLETE, OnStyleEvent); 
			
			styleLoader.addEventListener(StyleEvent.ERROR, OnStyleEvent); 
		}
		public function loadCssStyles(sources:Array):void{
			_sourcesUrl = sources;
			
			loadNextCssStyle();
		}
		private var _loadedCount:int = 0;
		private function OnStyleEvent(event:StyleEvent):void 
		{ 
			if(event.type == StyleEvent.COMPLETE) 
			{ 
				if(_sourcesUrl.length == 0){
					dispatchEvent(new AppEvent(AppEvent.VIEWR_STYLE_LOAD_COMPLETE));
				}else{
					loadNextCssStyle();
				}
			}else if(event.type == StyleEvent.ERROR) 
			{ 
				trace(event.errorText); 
			} 
		} 
		
		public static function  getInstance():IViewerStyleManager
		{
			if(instance == null){
				instance = new ViewerStyleManager();
			}
			return instance;
		}
		public static function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void{
			getInstance().addEventListener(type,listener,useCapture,priority,useCapture);
		}
		public static function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void{
			getInstance().removeEventListener(type,listener,useCapture);
		}
	}
}